$(function(){
	var code  = getUrlParam("gridCode");
	$.ajax({
			  url : URL.FRAMEWORK+"/autoGrid/getGrigConfig?gridCode="+code,
			  success : function(response){
				  initSearchForm(response.data.details,response.data.dictionarys);
				  initWebResource(response.data.resources);
				  initGrid(response.data.grid,response.data.details,response.data.dictionarys); 
				  initEvent(response.data.resources);
				  initDepthSearch(response.data.details,response.data.dictionarys);
			  }
	});
})

 
function getUrlParam(paramName) {
            var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
}

function initSearchForm(details,dictionarys){
var config = 
    { 
	     lableWidth:  150,
		 elementWidth:200,   
		 isLable : false,
		 models : []
	};
    var dicts = $.dictionaryUtil.formatArray(dictionarys);
    
	var type = ["select","radio","checkbox"]; 
	for(var i = 0 ; i < details.length; i++){
		var detail =  details[i];
		if(!detail.isFixedQuery){
			continue;
		}    
		var model = {"field":detail.columnAlias,"lable":detail.name,"type":detail.elementType};
		
		//日期
		if(detail.elementType == "date"){
			var formatter = detail.formatter ? detail.formatter :'yyyy-MM-dd HH:mm:ss' 
			model.options = {css:"Wdate",events:[{event:"click",method:WdatePicker,param:{dateFmt:formatter,alwaysUseStartDate:true}}]};
		//字典
		}else if($.inArray(detail.elementType,type) > -1){
			model.options = {data:dicts[detail.dictCode],key:"key",value:"value"};
		}
		config.models.push(model);
	} 
   $("#auto_search_form").selfform(config);
}

function initGrid(grid,details,dictionarys){ 
 
    var dictMap =  $.dictionaryUtil.formatMap(dictionarys); 
    var pageSizeJson = dictMap["grid_page_size"];
    var pageSize = [];
    for(var size in pageSizeJson){
    	pageSize.push(pageSizeJson[size]);
    } 
  var config = 
     {
        url: URL.FRAMEWORK+'/autoGrid/query?gridCode='+grid.code,         //请求后台的URL（*）
        method: 'get',                      //请求方式（*）
        toolbar: '#auto_operation',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        queryParams: function(params){
        	var formdata =  $("#auto_search_form").selfform("getData");
        	$.extend(params,formdata);
        	return params;
        },          //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pagination: Boolean(grid.isPage),   //是否显示分页（*）
        pageNumber:1,                       //初始化加载第一页，默认第一页
        pageSize: 5,                        //每页的记录行数（*）
        pageList: pageSize,                 //可供选择的每页的行数（*）
        columns: [],
        showColumns: true,                  //是否显示所有的列
        uniqueId: "id",
        responseHandler : function(response){
        	return response.data;
       }
    };


	var elementType = ["select","radio","checkbox"];  
    config.columns.push({checkbox:true});
	for(var i = 0 ; i < details.length; i++){
		var detail =  details[i];
		var detailFun = function(){
			return detail;
		}
		var column = {"field":detail.columnAlias,"title":detail.name,visible:detail.isDisplay==2};
		//日期
	    if(detail.elementType == "date"){ 
	    	column.formatter = function(cellValue, rowRecord, rowIndex){
	    		return cellValue ? dateformat(cellValue) : "";
	    	}
	    }else if($.inArray(detail.elementType,elementType) > -1){
	    	
	    	   (function (detail) { 
	    	        column.formatter = function(value, row, index,field){ 
	   				 var dict = dictMap[detail.dictCode];
	   		   		 var v =  dict ? dict[value] : "";
	   				 return v || v > 0 ? v: "";
	   		     } 
	    	    })(detail);   
	     } 
	    config.columns.push(column);
	} 
	$('#auto_grid').bootstrapTable(config);
}

//初始化按钮
function initWebResource(response){
	if(!response){
		return ;
	}
	var operationHtml = "";
	for(var i = 0 ; i <response.length ; i++){
		var res = response[i]; 
		var iconJson = res.css ? JSON.parse(res.css) : {};
		operationHtml += "<button id='"+res.code+"' type='button' "+iconJson.attr+" class='"+iconJson.btn+" auto-grid-button'><span class='"+iconJson.icon+"' aria-hidden='true'>"+res.name+"</span></button>";
	}
	$("#auto_operation").append(operationHtml);
}

//初始化按钮事件
function initEvent(response){  
	if(!response){
		return ;
	}
	for(var i = 0 ; i <response.length ; i++){
		var res = response[i]; 
		switch (res.code) {
			case "add": //新增
				$("#"+res.code).on("click",function(){
					var code  = getUrlParam("gridCode");
					if(code = 'queryAutoGridConfig'){
						  window.location.href = URL.WEB_FRAMEWORK + '/templates/business/autoBootstrapGridConfig.html';
					}
				}) 
				break;
			case "edit": //修改
				$("#"+res.code).on("click",function(){
					var code  = getUrlParam("gridCode");
					if(code = 'queryAutoGridConfig'){
						var gridData = 	$('#auto_grid').bootstrapTable('getSelections'); 
						 if(!gridData || gridData.length < 1){
							 alert("选择修改的行");
							 return ;
						 } else if(gridData.length > 1){
							 alert("只能修改一行数据");
							 return ;
						 } 
						window.location.href = URL.WEB_FRAMEWORK + '/templates/business/autoBootstrapGridConfig.html?gridCode='+gridData[0].code;
					}
				}) 
				break;
			case "search": //查询
				$("#"+res.code).on("click",function(){
					$('#auto_grid').bootstrapTable('refresh');
				}) 
				break;
			case "repeat_search": //重置并查询
				$("#"+res.code).on("click",function(){ 
					$("#auto_search_form").selfform("reset");
					$('#auto_grid').bootstrapTable('refresh');
			    }) 
				break;
			case "depth_search": //深度查询 
				
	 		$("#"+res.code).on("click",function(){ 
			   $("#auto_depth_search").modal('show');
		    }) 
				break;	
			case "repeat": //重置
				$("#"+res.code).on("click",function(){ 
					$("#auto_search_form").selfform("reset");
			    }) 
				break;	 
			case "remove": //删除 
				$("#"+res.code).on("click",function(){
				  
					var code  = getUrlParam("gridCode");
					if(code == "queryAutoGridConfig"){
						var gridData = 	$('#auto_grid').bootstrapTable('getSelections'); 
						var codes = [];
						for(var i = 0 ; i < gridData.length ; i++){
							codes.push(gridData[i].code);
						} 
						var data = {"gridCodes":codes};  
						  $.ajax({
							  url :  URL.FRAMEWORK + "/autoGridConfig/delete",
							  type:"post",
							  data:data,
							  traditional:true,
							  success : function(response){ 
								 $('#auto_grid').bootstrapTable('refresh');
							  }
						  });
					} 
			    })  
				break;
			default:
				break;
		}
	 } 
}
 
//深度(普通、高级)查询
function initDepthSearch(details,dictionarys){ 
	
    var dicts = $.dictionaryUtil.formatArray(dictionarys);
	var type = ["select","radio","checkbox"]; 
    var operationSymbol =  dicts["grid_depth_search_operation"];
    var formIds = ["#auto_depth_ordinary_search_form","#auto_depth_senior_search_form"];
    for(var a = 0 ; a < formIds.length ; a++ ){
    	var config = 
        { 
    	     lableWidth:  150,
    		 elementWidth:200, 
    		 isLable:false,
    		 models : [ ]
    	};
        var eleArrays = [];
        var index = -1;
    	for(var i = 0 ; i < details.length; i++){
    		var detail =  details[i];
    		if(!detail.isFixedQuery){
    			continue;
    		}
            ++index;   		
    		var model = {"field":"fileldVal"+index,"name":"fileldVal","lable":detail.name,"type":detail.elementType}; 
    		//日期
    		if(detail.elementType == "date"){
    			var formatter = detail.formatter ? detail.formatter :'yyyy-MM-dd HH:mm:ss' 
    			model.options = {css:"Wdate",events:[{event:"click",method:WdatePicker,param:{dateFmt:formatter,alwaysUseStartDate:true}}]};
    		//字典
    		}else if($.inArray(detail.elementType,type) > -1){
    			model.options = {data:dicts[detail.dictCode],key:"key",value:"value"};
    		}
    		
    	   var   models  = [];
    	   models.push(
    			{"field":"addDepthSearch"+index,"name":"addDepthSearch", "type":"button","outCss":"depth_add_search_out","inCss":"glyphicon glyphicon-plus btn btn-default",line:true,lable:""},
    		    ( 
                  a == 0 ? 
    		      {"field":"LeftBrackets"+index,"name":"LeftBrackets", "type":"hidden","lable":"选择左括号", "value":"("}
                  :
    		      {"field":"LeftBrackets"+index,"name":"LeftBrackets", "type":"select","lable":"选择左括号",options:{data:[{"key":"(","value":"左括号"}]}}
    		    ),
    		    {"field":"fieldName"+index, "name":"fieldName", "type":"hidden", "value":detail.columnAlias},
    		    {"field":"content"+index,"name":"content",  "type":"content" ,"content":detail.name},
    		    {"field":"operation"+index,"name":"operation",  "type":"select" ,"lable":"操作符",options:{data:operationSymbol} },
    		    model,
    		    (
    		      a == 0 ?
    		      {"field":"rightBrackets"+index,"name":"rightBrackets", "type":"hidden","lable":"选择右括号", "value":")"}
    		      :
    		      {"field":"rightBrackets"+index,"name":"rightBrackets", "type":"select","lable":"选择右括号",options:{data:[{"key":")","value":"右括号"}]}}
    		    ),
    		    ( 
    		      a == 0 ?
    		      {"field":"linkSymbol"+index,"name":"linkSymbol", "type":"hidden","lable":"链接", "value":"and"}
    		      :
    		      {"field":"linkSymbol"+index,"name":"linkSymbol","type":"select","lable":"链接",options:{data:[{"key":"or","value":"or"},{"key":"and","value":"and"}]}}
    		      )
    	   ); 
    	   eleArrays.push(models);
    	   config.models =   config.models.concat(models);
    	}  
        $(formIds[a]).selfform(config); 
 
        //保存 models模板
        var eles = $(formIds[a]).find(".depth_add_search_out");
        for(var b = 0 ; b < eleArrays.length ; b++){
        	eleArrays[b][0].inCss = null;
        	$(eles[b]).data("models",eleArrays[b]);
        }
        
       if(eleArrays.length > 1){
    	   var eleGroupAmount = eleArrays[0].length-1;
           $(formIds[a]).on("click","[id^=addDepthSearch]",function(event){
           	var target = $(event.target);
           	var form   = target.parents("form");
           	var group    = target.parents(".form-group");
   			var index  = form.find(".form-group").index(group);
   			var models = target.parents(".depth_add_search_out").data("models");
   			models[0].inCss = "add_search_hidden";
   		 	form.selfform("addElement",index+eleGroupAmount,models); 
           }); 
       }
      
        
    	var option = {"show":false};
    	$(formIds[a]).modal(option); 
    }  
}
 

//解析sql
function analysis(){
	
	 var activeId = $("#depth_search_tabs li.active a").attr("href");
	 
	 var activeForm = $(activeId).find("form");

	 var data = activeForm.selfform("serializable");
	 
	 var size = activeForm.find("[id^=LeftBrackets]").size();
	 
	 var elements = ["LeftBrackets","fieldName","operation","rightBrackets","linkSymbol"];
	 
	 var sql = "";
	 for(var i = 0 ; i < size ; i++){
		 for(var j = 0 , len = elements.length; j < len ; j++ ){  
		 
			 var value = data["fileldVal"] instanceof Array ?  data["fileldVal"][i] : i==0 ? data["fileldVal"] : null ;
			 if(!value){ continue; }
			 var element = elements[j];  
			 if(element != 'operation'){
				 sql += data[element][i]+"  ";
				 continue;
			 } 
		
			 var operation = data["operation"] instanceof Array ? data["operation"][i] : data["operation"] ;
			 switch (operation) {
				case "like":
					 sql += " like '%" + value + "%'  ";
					break;
				case "leftLike":
					 sql += " like '%" + value +"'  ";
					break;
				case "rightLike":
					 sql += " like '%" + value +"'  ";
					break; 
				case "equals":
					 sql += " = "+ value +"  ";
					break;
				case "greater":
					 sql += " > "+ value +"  ";
					break;
				case "less":
					 sql += " < "+ value +"  ";
					break;
				case "greaterEquals":
					 sql += " >= "+ value +"  ";
					break;
				case "lessEquals":
					 sql += " <= "+ value +"  ";
					break;
				case "in":
					 sql += " in ("+ value +" ) ";
					break; 
				default:
					break;
			} 
			 
		 }
	 } 
    sql = sql.trim().replace(/(and|or)$/,"");   
    $(activeId).find("div.sql").html(sql); 
    errorAlert(sql);
 
}

//深度查询后台
function depthSearch(){
     var activeId = $("#depth_search_tabs li.active a").attr("href"); 
	 var activeForm = $(activeId).find("form"); 
	 var data = activeForm.selfform("serializable");
	 
	 var elements = ["LeftBrackets","fieldName","operation","fileldVal","rightBrackets","linkSymbol"];
	 
	 var fileldVal = data["fileldVal"];
	 
	 var fileldVals = fileldVal instanceof Array ? fileldVal : [fileldVal];
	 
 
	 var jsonArray = [];
	 for(var i = 0 ; i < fileldVals.length ; i++){
		  var json = {}; 
		  for(var j = 0 ; j < elements.length ; j++){ 
			  var eleVals = data[elements[j]];
			  json[elements[j]] = eleVals instanceof Array ? eleVals[i] : i == 0 ? eleVals : null;  
		  }
		  jsonArray.push(json);
	 }     
	 var params = {query:{depthParams:JSON.stringify(jsonArray)}};
	 $('#auto_grid').bootstrapTable('refresh',params); 
	 $("#auto_depth_search").modal('hide')
}


function errorAlert(sql){  
	var l = sql.match(/\(+/g);
	var r = sql.match(/\)+/g);
	var warning = $("#alert-warning");
	if((l ? l.length : 0) === (r ? r.length : 0)){
		warning.html("");
		return;
	} 
	var warningHtml = '<div id ="depth_search_error" class="alert alert-warning">	<a href="#" class="close alert-close" data-dismiss="alert">&times;</a>	<strong>警告！</strong>高级查询sql有误</div>'; 
	warning.html(warningHtml);
	$("#depth_search_error").alert(); 
	var width   = warning.width();
	var height  = warning.height();
	var dwidth  =  window.screen.width;
	var dheight =  window.screen.height; 
	warning.css({"left":(dwidth-width)/2.5,"top":(dheight-height)/3});
}


